#include "hmc5883.h"
#include "i2cdrive.h"

mI2CTypedef_t Hmc5883I2c;

static void i2c_SdaH(void){
	HAL_GPIO_SetInOut(GPIOC, GPIO_PIN_2, ENABLE, DISABLE);
	HAL_GPIO_WritePin(GPIOC, GPIO_PIN_2, GPIO_PIN_RESET);
}

static void i2c_SdaL(void){
	HAL_GPIO_SetInOut(GPIOC, GPIO_PIN_2, ENABLE, ENABLE);
	HAL_GPIO_WritePin(GPIOC, GPIO_PIN_2, GPIO_PIN_RESET);
}

static void i2c_SclH(void){
	HAL_GPIO_SetInOut(GPIOC,GPIO_PIN_3, ENABLE, DISABLE);
	HAL_GPIO_WritePin(GPIOC, GPIO_PIN_3, GPIO_PIN_RESET);
}

static void i2c_SclL(void){
	HAL_GPIO_SetInOut(GPIOC, GPIO_PIN_3, ENABLE, ENABLE);
	HAL_GPIO_WritePin(GPIOC, GPIO_PIN_3, GPIO_PIN_RESET);
}

static u8 i2c_ReadSda(void){
	return HAL_GPIO_ReadPin(GPIOC, GPIO_PIN_2);
}

static u8 i2c_ReadScl(void){
	return HAL_GPIO_ReadPin(GPIOC, GPIO_PIN_3);
}

//初始化i2c驱动以及IO
void HMC5883_i2c_init(void)
{					
	GPIO_InitTypeDef GPIO_Initure;

	GPIO_Initure.Pin = GPIO_PIN_2| GPIO_PIN_3;
	GPIO_Initure.OutputEn = DISABLE;
	GPIO_Initure.InputEn = ENABLE;
	GPIO_Initure.PullupEn = DISABLE;
	HAL_GPIO_Init(GPIOC, &GPIO_Initure);

	Hmc5883I2c.IIC_InitPort=0;							
	Hmc5883I2c.IIC_SDA_H=i2c_SdaH;
	Hmc5883I2c.IIC_SDA_L=i2c_SdaL;
	Hmc5883I2c.IIC_SCL_H=i2c_SclH;
	Hmc5883I2c.IIC_SCL_L=i2c_SclL;
	Hmc5883I2c.IIC_READ_SDA=i2c_ReadSda;
	Hmc5883I2c.IIC_READ_SCL=i2c_ReadScl;
}
//从uWriteAddress地址开始写入len字节数据
void HMC5883_i2c_write(u8 uWriteAddress,u8 *buf,u8 len)
{
	i2c_Start(&Hmc5883I2c);
	i2c_SendByte(&Hmc5883I2c, HMC5883_I2C_ADDR |I2C_WR);
	i2c_WaitAck(&Hmc5883I2c);
	i2c_SendByte(&Hmc5883I2c,(uWriteAddress) & 0xFF);
	i2c_WaitAck(&Hmc5883I2c);
	while(len--){
		i2c_SendByte(&Hmc5883I2c,*buf++);
		i2c_WaitAck(&Hmc5883I2c);
	}
	i2c_Stop(&Hmc5883I2c);
}
//从uWriteAddress地址开始读出len字节数据
u8 HMC5883_i2c_read(u8 uReadAddress,u8 *buf,u8 len)
{
	i2c_Start(&Hmc5883I2c);
	i2c_SendByte(&Hmc5883I2c, HMC5883_I2C_ADDR |I2C_WR);
	if(1==i2c_WaitAck(&Hmc5883I2c)){	//ERROR
		return 0;
	}
	i2c_SendByte(&Hmc5883I2c,uReadAddress);
	if(1==i2c_WaitAck(&Hmc5883I2c)){	//ERROR
		return 0;
	}
	i2c_Start(&Hmc5883I2c);
	i2c_SendByte(&Hmc5883I2c, HMC5883_I2C_ADDR |I2C_RD);
	if(1==i2c_WaitAck(&Hmc5883I2c)){	//ERROR
		return 0;
	}
	while(len-->1){
		*buf++ = i2c_ReadByte(&Hmc5883I2c);
		i2c_Ack(&Hmc5883I2c);
	}
	*buf++ = i2c_ReadByte(&Hmc5883I2c);
	i2c_NAck(&Hmc5883I2c);
	i2c_Stop(&Hmc5883I2c);
	return 1;//正常返回
}
//初始化
void HMC5883_init(void)
{
	u8 ret;
	u8 buf[6];
	HMC5883_i2c_init();							//注册I2C驱动
	//ret=i2c_CheckDevice(&Hmc5883I2c, HMC5883_I2C_ADDR);
	//void uart8_send(u8 *buf,u16 len);
	//if (ret == 0) {
	//	uart8_send("电子罗盘初始化成功！",29);
	//}
	//else {
	//	uart8_send("电子罗盘初始化失败！", 29);
	//}
	buf[0] = 0;
	HMC5883_i2c_write(0x02,buf,1);

}


